<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use qcloudcos\Cosapi;
use think\auth\Auth;
use app\admin\model\AdminUsers as Users;

class Baseic extends Controller
{
  protected $userId  ;      // 用户ID
  protected $userName ;     // 用户名
  protected $model;         // 模型

  protected function _initialize()
  {
      parent::_initialize();

      if ($this->checkLogin()) {
        $this->checkAuth();
      }else {
        $this->redirect('Login/index');
      }


      if(method_exists($this,'__auto')){
        $this->__auto();
      }
  }

    // 检测登录状态
    private function checkLogin(){
      /**
      * 检测用户存在、登录
      */
      if (!empty(session('admin_user_id'))){
          $this->userId   = session('admin_user_id');
          $this->userName = session('admin_user_name');

          $this->assign('user_id',$this->userId);
          $this->assign('user_name',$this->userName);

          return true;
      }else{
          return false;
      }


    }

    // 检测用户权限
    private function checkAuth(){
      // 获取auth实例

      $db    = new Users();
      $data  =$db->getUserGroup($this->userId);

      session('is_admin',$data->is_admin);

      if (!$data->is_admin) {
         // 获取auth实例
         $auth = Auth::instance();

         $controller = request()->controller();         //  $module     = request()->module();
         $action     = request()->action();

         if(!$auth->check($controller . '/' . $action, $this->userId)){
           p('你没有权限访问:'.$controller . '/' . $action);
           exit();
          //   $this->error('你没有权限访问');
         }
      }
      unset($data);
    }

    // 多文件上传
    public function uploade($pic){
        // 获取表单上传文件
        $ret = new Cosapi;      
        $files = request()->file($pic);
        foreach($files as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                // echo $info->getFilename(); 
                $bucket = 'aks';
                $src = '../public/uploads/'.date('Ymd',time()).'/'.$info->getFilename();
                $dst = '/aks_class/'.$info->getFilename(); 
                Cosapi::setTimeout(180);
                Cosapi::setRegion('gz');
                $list = $ret->upload($bucket, $src, $dst);
                if($list['code'] == '0'){
                    // unlink($src);
                }else{
                    unlink($src);
                    return $this->error('图片上传有误');
                }
                $path[] = str_replace("file","cosgz",$list['data']['access_url']);
            }else{
                // 上传失败获取错误信息
                return $file->getError();
            }    
        }
        return $path;
    }
}
